package cn.wolfcode.demo.controller;


import cn.wolfcode.demo.Json.JsonResult;
import cn.wolfcode.demo.domain.User;
import cn.wolfcode.demo.service.IUserService;
import cn.wolfcode.demo.service.MongoUserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MongoUserService mUserService;
    @Autowired
    private JavaMailSender mailSender;
    @GetMapping("/list")
    public Object list(){
        List<User> list = userService.list();
        return list;

    }

    @GetMapping("/get")
    public Object get(User user){
        User users = userService.findUserById(user.getUsername());
        SimpleMailMessage Message=new SimpleMailMessage();
        Message.setFrom("1365506782@qq.com");
        Message.setSubject("作业");

        if(users!=null) {
            if (users.getPassword().equals(user.getPassword())) {
                Message.setText("用户名："+users.getUsername()+"密码："+users.getPassword());
                Message.setTo("1365506782@qq.com");
                mailSender.send(Message);
                return new JsonResult();
            } else {
                return new JsonResult(false, "密码错误");
            }
        }else {
            return new JsonResult(false, "用户名不存在");
        }
    }
    @RequestMapping("/save")
    public Object save(User user) {
        User userByUserName = userService.getUserByUserName(user.getUsername());
        if (userByUserName != null) {
            return new JsonResult(false,"用户名已存在,请重新注册");
        } else {
            boolean save = userService.save(user);
            if (save) {
                ValueOperations valueOperations = redisTemplate.opsForValue();
                valueOperations.set("user" + user.getUsername(), user);
                mUserService.save(user);
                return new JsonResult();
            } else {
                return new JsonResult(false, "注册失败!");
            }
        }
    }
}
